const db = require('../Mysql/sql');
const {
	nanoid
} = require('nanoid');
const {
	tree
} = require("../../utils/common.js")

const nav = {
	//新增导航
	setUserMenuList(req, res) {
		if (req.body.children) delete req.body.children
		const {
			id,
			...body
		} = req.body

		const sql2 = `select * from navigation where nid=?`
		db.query(sql2, body.nid, (err2, results2) => {
			if (err2) return res.cc(err2)
			let sql = ``
			sql = results2.length ? `update navigation set ? where id=${results2[0].id}` :
				`insert into navigation set ?`

			db.query(sql, body, (err, results) => {
				if (err) return res.cc(err)
				if (results.affectedRows !== 1) return res.cc('修改失败')
				res.cc('修改成功', 200)
			})
		})
	},
	//获取导航
	getUserMenuList(req, res) {
		const sql = `select * from navigation 
		${req.query.searchValue?`where label like %${req.query.searchValue}%`:''}
		${req.query.auth?`where id in (${req.query.auth})`:''}
		`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			res.send({
				status: 200,
				msg: '获取成功',
				data: tree(results, 'nid', 'fid')
			})
		})
	},
	//删除
	delUserMenuList(req, res) {
		let sql = `delete from navigation where nid=?`
		db.query(sql, req.body.id, (err, results) => {
			if (err) return res.cc(err)
			res.cc('删除成功', 200)
		})
	},
	// 获取id
	getNavigationId(req, res) {
		const id = nanoid()
		res.cc('获取成功', 200, id)
	},

	//获取表单
	getCustomFrom(req, res) {
		const sql = `select * from customfrom c
		${req.query.id?`where c.id=${req.query.id}`:``}
		${req.query.describe?`where c.describe like '${req.query.describe}' and type=${req.query.type}`:``}`

		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			res.send({
				status: 200,
				msg: '获取成功',
				data: results
			})
		})
	},
	//删除
	delCustomFrom(req, res) {
		let sql = `delete from customfrom where nid=?`
		db.query(sql, req.body.id, (err, results) => {
			if (err) return res.cc(err)
			res.cc('删除成功', 200)
		})
	},
	//设置表单
	setCustomFrom(req, res) {
		const {
			id,
			...body
		} = req.body
		const sql2 = `select * from customfrom where nid=?`
		db.query(sql2, body.nid, (err2, results2) => {
			if (err2) return res.cc(err2)
			let sql = ``
			sql = results2.length ? `update customfrom set ? where id=${results2[0].id}` :
				`insert into customfrom set ?`

			db.query(sql, body, (err, results) => {
				if (err) return res.cc(err)
				if (results.affectedRows !== 1) return res.cc('修改失败')
				res.cc('修改成功', 200)
			})
		})
	}
}
module.exports = nav